<!-- eslint-disable vue/valid-v-for -->
<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" :title="pageTitle" />
    </div>
    <n-form
      :model="formValues"
      :rules="rules"
      label-placement="left"
      ref="formRef"
      class="py-4"
      :label-width="80"
    >
      <n-card
        :bordered="false"
        title="基本信息"
        class="proCard"
        size="large"
        :segmented="{ content: true }"
      >
        <n-grid cols="2" responsive="screen">
          <n-grid-item offset="0">
            <n-form-item label="盲盒名称" path="blindBoxName">
              <n-input placeholder="请输入盲盒名称" v-model:value="formValues.blindBoxName" />
            </n-form-item>
            <!-- <n-form-item label="背景图" path="backImg">
              <n-input placeholder="请输入背景图" v-model:value="formValues.backImg" />
            </n-form-item>
            <n-form-item label="盲盒标题图" path="blindBoxImg">
              <n-input placeholder="请输入盲盒标题图" v-model:value="formValues.blindBoxImg" />
            </n-form-item> -->
            <n-form-item label="盲盒标题图" path="blindBoxImg">
              <BasicUpload
                :data="{ scene: 'blind' }"
                name="file"
                :width="100"
                :height="100"
                :maxSize="2"
                :maxNumber="1"
                v-model:value="uploadTitleList"
                helpText="单个文件不超过2MB，最多只能上传1个文件"
              />
            </n-form-item>

            <n-form-item label="盲盒背景图" path="backImg">
              <BasicUpload
                :data="{ scene: 'blind' }"
                name="file"
                :width="100"
                :height="100"
                :maxSize="2"
                :maxNumber="1"
                v-model:value="uploadBackList"
                helpText="单个文件不超过2MB，最多只能上传1个文件"
              />
            </n-form-item>
          </n-grid-item>
        </n-grid>
      </n-card>
      <n-card
        :bordered="false"
        title="用户端显示概率"
        class="mt-2 proCard"
        size="large"
        :segmented="{ content: true }"
      >
        <div class="desc"> 在用户端展示的百分比概率信息，概率总和必须为100，否则无法提交 </div>
        <div class="goods-grade">
          <div class="goods-grade-item" v-for="(item, index) in showGoodsTags" :key="index">
            <img :src="item.img" />
            <span>{{ item.name }}</span>
            <n-input-number
              :precision="3"
              v-model:value="item.odds"
              placeholder="请输入概率"
              :show-button="false"
            />
          </div>
        </div>
      </n-card>
      <n-card
        :bordered="false"
        title="实际概率(权重)"
        class="mt-2 proCard"
        size="large"
        :segmented="{ content: true }"
      >
        <div class="desc">
          系统会自动计算每个档次的概率，只需要填写每个档次的权重，权重越高，概率越大
        </div>
        <div class="goods-grade">
          <div class="goods-grade-item" v-for="(item, index) in goodsTags" :key="index">
            <img :src="item.img" />
            <span>{{ item.name }}</span>
            <n-input-number
              :precision="0"
              v-model:value="item.odds"
              placeholder="请输入概率"
              :show-button="false"
            />
          </div>
        </div>
        <div class="goods-select">
          <BasicSelectGoods
            :page-size="10"
            :selected="goodsSelectId"
            @update:complete="handleSelectComplete"
          />
          <!-- <n-data-table :columns="columns" /> -->
          <BasicTable
            :columns="columns"
            :dataSource="goodsSelectValue"
            :row-key="(row) => row.id"
            ref="goodsActionRef"
            :actionColumn="goodsActionColumn"
            :pagination="false"
            :scroll-x="1090"
          />
        </div>
      </n-card>

      <n-card
        :bordered="false"
        title="销售信息"
        class="mt-2 proCard"
        size="large"
        :segmented="{ content: true }"
      >
        <n-grid cols="2" responsive="screen">
          <n-grid-item offset="0">
            <n-form-item label="单次价格(仅展示)" label-width="130" path="price">
              <n-input-number
                :precision="2"
                v-model:value="formValues.price"
                placeholder="请输入单次价格"
                :show-button="false"
              >
                <template #prefix> ￥ </template>
              </n-input-number>
            </n-form-item>
            <n-form-item label="价格规则" label-width="130" path="priceRules">
              <n-data-table :columns="priceRuleColumns" :data="priceRuleData" />
            </n-form-item>
          </n-grid-item>
        </n-grid>
      </n-card>
      <div class="tools-block" ref="toolsRef">
        <n-card class="mt-2 proCard" hoverable>
          <n-space justify="center" style="">
            <n-button type="primary" size="large" :loading="formBtnLoading" @click="formGoodsSubmit"
              >提交</n-button
            >
            <n-button size="large" @click="resetGoodsFrom">重置</n-button>
          </n-space>
        </n-card>
      </div>
      <div class="white-block" ref="containerRef"></div>
    </n-form>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, reactive, ref, h} from 'vue';
  import { useMessage, NButton, useDialog } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { columns } from './lib/goodsColumns';
  import { priceRuleColumns } from './lib/priceRuleColumns';
  import { saveBlindBox, getBlindBox, updateBlindBox } from '@/api/blindBox/blindBox';
  import BasicSelectGoods from '@/components/Shop/SelectGoods/BasicSelectGoods.vue';
  import { useTabsViewStore } from '@/store/modules/tabsView';
  import { ResultEnum } from '@/enums/httpEnum';
  import { useRoute, useRouter } from 'vue-router';

  const router = useRouter();
  const route = useRoute();
  const tabsViewStore = useTabsViewStore();

  const containerRef = ref<HTMLElement | undefined>(undefined);
  const toolsRef = ref<HTMLElement | undefined>(undefined);
  // 暂时写死  后期更换为可配置
  const goodsTags = ref([
    {
      id: 'bronze',
      img: 'https://yashangxuan.oss-cn-beijing.aliyuncs.com/blind/grade1.png',
      name: '青铜',
      odds: null,
    },
    {
      id: 'silver',
      img: 'https://yashangxuan.oss-cn-beijing.aliyuncs.com/blind/grade2.png',
      name: '白银',
      odds: null,
    },
    {
      id: 'gold',
      img: 'https://yashangxuan.oss-cn-beijing.aliyuncs.com/blind/grade3.png',
      name: '黄金',
      odds: null,
    },
    {
      id: 'platinum',
      img: 'https://yashangxuan.oss-cn-beijing.aliyuncs.com/blind/grade4.png',
      name: '铂金',
      odds: null,
    },
    {
      id: 'diamond',
      img: 'https://yashangxuan.oss-cn-beijing.aliyuncs.com/blind/grade5.png',
      name: '钻石',
      odds: null,
    },
  ]);
  const showGoodsTags = ref([
    {
      id: 'bronze',
      img: 'https://yashangxuan.oss-cn-beijing.aliyuncs.com/blind/grade1.png',
      name: '青铜',
      odds: null,
    },
    {
      id: 'silver',
      img: 'https://yashangxuan.oss-cn-beijing.aliyuncs.com/blind/grade2.png',
      name: '白银',
      odds: null,
    },
    {
      id: 'gold',
      img: 'https://yashangxuan.oss-cn-beijing.aliyuncs.com/blind/grade3.png',
      name: '黄金',
      odds: null,
    },
    {
      id: 'platinum',
      img: 'https://yashangxuan.oss-cn-beijing.aliyuncs.com/blind/grade4.png',
      name: '铂金',
      odds: null,
    },
    {
      id: 'diamond',
      img: 'https://yashangxuan.oss-cn-beijing.aliyuncs.com/blind/grade5.png',
      name: '钻石',
      odds: null,
    },
  ]);

  const priceRuleData = ref([
    {
      id: 'one',
      name: '一发入魂',
      buyNum: 1,
      price: 0,
    },
    {
      id: 'two',
      name: '欧气三连',
      buyNum: 3,
      price: 0,
    },
    {
      id: 'five',
      name: '霸气五连',
      buyNum: 5,
      price: 0,
    },
  ]);

  const goodsActionColumn = reactive({
    width: 220,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record, index) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '删除',
            type: 'error',
            onClick: handleDelSelectGoods.bind(null, record, index),
          },
        ],
      });
    },
  });
  const dialog = useDialog();
  const goodsSelectValue = ref<object[]>([]);
  const goodsSelectId = ref<number[]>([]);
  const rules = {
    blindBoxName: {
      required: true,
      message: '请输入盲盒名称',
      trigger: 'blur',
    },
    blindBoxImg: {
      required: true,
      message: '请输入上传盲盒图片',
      trigger: 'blur',
    },
    backImg: {
      required: true,
      message: '请上传盲盒背景图',
      trigger: 'blur',
    },
    price: {
      required: true,
      message: '请输入销售价格',
      trigger: 'blur',
      type: 'number',
      validator: (_rule: any, value: number) => {
        if (value === 0) {
          return Promise.reject('请输入销售价格');
        } else {
          return Promise.resolve();
        }
      },
    },
  };

  const formValues = reactive({
    id: 0,
    blindBoxName: '',
    blindBoxImg: '',
    backImg: '',
    price: 0.0,
    priceRules: [],
    produceRules: [],
    showProduceRules: [],
    status: 0,
    goodsList: null,
    createTime: 0,
  });
  const formValuesBak = { ...formValues };
  const uploadTitleList = ref([]);
  const uploadBackList = ref([]);
  const formBtnLoading = ref(false);
  const formRef: any = ref(null);
  const message = useMessage();

  const pageTitle = ref('添加盲盒');

  const isEdit = ref(false);

  const goodsActionRef = ref();

  function handleSelectComplete(goodsList: object[]) {
    goodsList.forEach((item) => {
      let goods = {};
      goods['goodsTags'] = goodsTags.value;
      goods['goodsImg'] = item['goodsImgs'][0];
      goods['goodsId'] = item['id'];
      goods['goodsName'] = item['goodsName'];
      goods['goodsPrice'] = item['goodsPrice'];
      goodsSelectValue.value.push(goods);
      goodsSelectId.value.push(item['id']);
    });
  }

  onMounted(async () => {
    // 动态设置工具条宽度
    let width = containerRef.value?.offsetWidth;
    toolsRef.value!.style.width = width + 'px';
    const title = route.params.title?.toString();
    const blindId = route.params.id;
    pageTitle.value = title === undefined ? '添加盲盒' : title;
    if (blindId) {
      isEdit.value = true;
      let response = await getBlindBox({ id: blindId });
      if (response.code == ResultEnum.SUCCESS) {
        const blindBoxInfo = response.result;
        Object.assign(formValues, blindBoxInfo);
        Object.assign(formValuesBak, blindBoxInfo);
        // 图片 概率 商品列表赋值
        uploadTitleList.value[0] = blindBoxInfo.blindBoxImg;
        uploadBackList.value[0] = blindBoxInfo.backImg;
        priceRuleData.value = blindBoxInfo.priceRules;
        goodsTags.value = blindBoxInfo.produceRules;
        showGoodsTags.value = blindBoxInfo.showProduceRules;
        goodsSelectValue.value = blindBoxInfo.goodsList;
        blindBoxInfo.goodsList?.forEach((item: any) => {
          item['goodsTags'] = goodsTags.value;
          goodsSelectId.value.push(item.goodsId);
        });
      } else {
        message.error('获取盲盒信息失败');
      }
      // const goodsInfo = response.result;
      // uploadList.value = goodsInfo.goodsImgs;
      // //console.log(uploadList.value);
    }
  });

  function formGoodsSubmit(_e: { preventDefault: () => void }) {
    _e.preventDefault();
    let odds = 0;
    for (let i = 0; i < showGoodsTags.value.length; i++) {
      let item = showGoodsTags.value[i];
      console.log(item);
      if (!item.odds) {
        message.error('请填写完整概率信息');
        return;
      } else {
        odds += Number(item.odds);
      }
    }
    if (odds != 100) {
      message.error('概率总和必须为100,' + odds);
      return;
    }
    formBtnLoading.value = true;
    formValues.priceRules = priceRuleData.value;
    formValues.produceRules = goodsTags.value;
    formValues.showProduceRules = showGoodsTags.value;
    formValues.goodsList = goodsSelectValue.value;
    console.log(formValues);
    formValues.backImg = uploadBackList.value[0];
    formValues.blindBoxImg = uploadTitleList.value[0];
    formRef.value.validate(async (errors: any) => {
      if (!errors) {
        let response;
        if (formValues.id === 0) {
          response = await saveBlindBox(formValues);
        } else {
          response = await updateBlindBox(formValues);
        }
        const { message: msg, code } = response;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
          tabsViewStore.closeCurrentTab(route);
          router.push({ name: 'blindBoxList' });
        } else {
          message.error(msg);
        }
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  function resetGoodsFrom() {
    // 清空
    Object.assign(formValues, formValuesBak);
  }

  function handleDelSelectGoods(record, index) {
    dialog.info({
      title: '提示',
      content: `您确定想删除吗?`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        goodsSelectValue.value.splice(index, 1);
        goodsSelectId.value.splice(index, 1);
      },
      onNegativeClick: () => {
        message.error('已取消');
      },
    });
  }
</script>

<style lang="less" scoped>
  .goods-select {
    margin-top: 20px;
  }
  .goods-grade {
    display: flex;
    align-items: center;
    margin-top: 20px;
    &-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      margin: 0 20px;
      img {
        width: 50px;
        height: 50px;
      }
      span {
        font-size: 20px;
        font-weight: bold;
      }
    }
  }

  .tools-block {
    position: fixed;
    bottom: 10px;
    z-index: 10;
    //width: 100%;
  }

  .white-block {
    height: 72px;
    width: 100%;
  }
</style>
